import React, { useEffect, useRef, useState } from 'react';
import { gsap } from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import './HeroSection.scss';

gsap.registerPlugin(ScrollTrigger);

interface ImageData {
  id: number;
  title: string;
  subtitle: string;
  description: string;
  category: string;
}

const HeroSection: React.FC = () => {
  const heroRef = useRef<HTMLDivElement>(null);
  const titleRef = useRef<HTMLDivElement>(null);
  const subtitleRef = useRef<HTMLDivElement>(null);
  const descriptionRef = useRef<HTMLDivElement>(null);
  const buttonsRef = useRef<HTMLDivElement>(null);
  const imageContainerRef = useRef<HTMLDivElement>(null);
  const imagesRef = useRef<HTMLDivElement[]>([]);
  const counterRef = useRef<HTMLDivElement>(null);
  const scrollIndicatorRef = useRef<HTMLDivElement>(null);
  
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isTransitioning, setIsTransitioning] = useState(false);
  const [isInitialized, setIsInitialized] = useState(false);

  const images: ImageData[] = [
    {
      id: 1,
      title: "山川壮景",
      subtitle: "Mountain Majesty",
      description: "用镜头捕捉山峦叠嶂的壮美瞬间",
      category: "风景摄影"
    },
    {
      id: 2,
      title: "海岸晨曦",
      subtitle: "Coastal Dawn",
      description: "记录海天一色的绝美日出",
      category: "风景摄影"
    },
    {
      id: 3,
      title: "星空银河",
      subtitle: "Starry Galaxy",
      description: "仰望星空，感受宇宙的浩瀚无垠",
      category: "天文摄影"
    },
    {
      id: 4,
      title: "森林秘境",
      subtitle: "Forest Mystery",
      description: "探索自然深处的神秘世界",
      category: "自然摄影"
    },
    {
      id: 5,
      title: "都市光影",
      subtitle: "Urban Lights",
      description: "城市夜景中的光与影交织",
      category: "城市摄影"
    }
  ];

  useEffect(() => {
    const currentImages = imagesRef.current;
    const totalImages = images.length;
    let scrollLocked = false;
    let lastScrollTime = 0;
    const debounceTime = 100; // 防抖时间

    const tl = gsap.timeline({ delay: 3 });

    // 定义switchToImage函数
    const switchToImage = (newIndex: number) => {
      if (newIndex === currentIndex || isTransitioning) return;
      
      setIsTransitioning(true);
      
      // 更新文字内容
      updateContent(newIndex);
      
      // 切换图片
      gsap.to(currentImages[currentIndex], {
        opacity: 0,
        scale: 0.95,
        duration: 0.6,
        ease: 'power2.out'
      });
      
      gsap.to(currentImages[newIndex], {
        opacity: 1,
        scale: 1,
        duration: 0.6,
        ease: 'power2.out',
        onComplete: () => {
          setCurrentIndex(newIndex);
          setIsTransitioning(false);
          
          // 如果是最后一张图片，更新滚动指示器
          if (newIndex === totalImages - 1 && scrollIndicatorRef.current) {
            const scrollText = scrollIndicatorRef.current.querySelector('.scroll-text');
            if (scrollText) {
              scrollText.textContent = '继续探索';
              gsap.to(scrollText, {
                scale: 1.05,
                duration: 0.3,
                ease: 'power2.out',
                yoyo: true,
                repeat: 1
              });
            }
          }
        }
      });
    };

    // 定义updateContent函数
    const updateContent = (index: number) => {
      const image = images[index];
      
      gsap.to([titleRef.current, subtitleRef.current, descriptionRef.current], {
        opacity: 0,
        y: -20,
        duration: 0.3,
        ease: 'power2.out',
        onComplete: () => {
          if (titleRef.current) titleRef.current.textContent = image.title;
          if (subtitleRef.current) subtitleRef.current.textContent = image.subtitle;
          if (descriptionRef.current) descriptionRef.current.textContent = image.description;
          
          gsap.to([titleRef.current, subtitleRef.current, descriptionRef.current], {
            opacity: 1,
            y: 0,
            duration: 0.5,
            ease: 'power2.out',
            stagger: 0.1
          });
        }
      });

      // 更新计数器
      if (counterRef.current) {
        counterRef.current.textContent = `${(index + 1).toString().padStart(2, '0')} / ${totalImages.toString().padStart(2, '0')}`;
      }
    };

    // 初始化动画
    tl.fromTo(titleRef.current,
      { y: 100, opacity: 0 },
      { y: 0, opacity: 1, duration: 1.2, ease: 'power3.out' }
    )
    .fromTo(subtitleRef.current,
      { y: 50, opacity: 0 },
      { y: 0, opacity: 1, duration: 1, ease: 'power2.out' },
      '-=0.8'
    )
    .fromTo(descriptionRef.current,
      { y: 30, opacity: 0 },
      { y: 0, opacity: 1, duration: 0.8, ease: 'power2.out' },
      '-=0.6'
    )
    .fromTo(buttonsRef.current,
      { y: 30, opacity: 0 },
      { y: 0, opacity: 1, duration: 0.8, ease: 'power2.out' },
      '-=0.4'
    )
    .fromTo(imageContainerRef.current,
      { scale: 0.9, opacity: 0 },
      { scale: 1, opacity: 1, duration: 1.5, ease: 'power2.out' },
      '-=1.2'
    )
    .fromTo(counterRef.current,
      { x: 50, opacity: 0 },
      { x: 0, opacity: 1, duration: 1, ease: 'power2.out' },
      '-=1'
    );

    // 设置初始图片显示 - 延迟执行确保元素已经渲染
    setTimeout(() => {
      currentImages.forEach((img, index) => {
        if (img) {
          gsap.set(img, {
            opacity: index === 0 ? 1 : 0,
            scale: index === 0 ? 1 : 0.95
          });
        }
      });
      setIsInitialized(true);
    }, 100);

    // 滚动监听器
    const handleScroll = (event: WheelEvent) => {
      const now = Date.now();
      
      // 防抖处理
      if (now - lastScrollTime < debounceTime) {
        event.preventDefault();
        return;
      }
      lastScrollTime = now;

      // 如果正在过渡中，阻止滚动
      if (isTransitioning) {
        event.preventDefault();
        return;
      }

      const delta = event.deltaY;
      const isScrollingDown = delta > 0;
      const isScrollingUp = delta < 0;

      // 向下滚动且还有图片可切换
      if (isScrollingDown && currentIndex < totalImages - 1) {
        event.preventDefault();
        setIsTransitioning(true);
        setCurrentIndex(currentIndex + 1);
        // 动画完成后重置过渡状态
        setTimeout(() => {
          setIsTransitioning(false);
        }, 600);
      }
      // 向上滚动且不是第一张图片
      else if (isScrollingUp && currentIndex > 0) {
        event.preventDefault();
        setIsTransitioning(true);
        setCurrentIndex(currentIndex - 1);
        // 动画完成后重置过渡状态
        setTimeout(() => {
          setIsTransitioning(false);
        }, 600);
      }
      // 已经是最后一张图片，允许正常滚动到下一个区域
      else if (isScrollingDown && currentIndex === totalImages - 1) {
        // 隐藏固定容器，允许页面滚动到下个区域
        gsap.to('.hero-container', {
          opacity: 0,
          duration: 0.5,
          ease: 'power2.out',
          onComplete: () => {
            // 滚动到下个区域
            const nextSection = document.querySelector('.gallery-section') as HTMLElement;
            if (nextSection) {
              nextSection.scrollIntoView({ behavior: 'smooth' });
            }
          }
        });
        event.preventDefault();
        return;
      }
      // 已经是第一张图片，允许向上滚动（如果有导航栏等）
      else if (isScrollingUp && currentIndex === 0) {
        // 允许正常滚动
        return;
      }
    };


    // 添加滚动监听
    const heroElement = heroRef.current;
    if (heroElement) {
      heroElement.addEventListener('wheel', handleScroll, { passive: false });
    }

    // 键盘导航
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'ArrowDown' && currentIndex < totalImages - 1 && !isTransitioning) {
        event.preventDefault();
        setIsTransitioning(true);
        setCurrentIndex(currentIndex + 1);
        setTimeout(() => {
          setIsTransitioning(false);
        }, 600);
      } else if (event.key === 'ArrowUp' && currentIndex > 0 && !isTransitioning) {
        event.preventDefault();
        setIsTransitioning(true);
        setCurrentIndex(currentIndex - 1);
        setTimeout(() => {
          setIsTransitioning(false);
        }, 600);
      }
    };

    document.addEventListener('keydown', handleKeyDown);

    return () => {
      tl.kill();
      ScrollTrigger.getAll().forEach(trigger => trigger.kill());
      if (heroElement) {
        heroElement.removeEventListener('wheel', handleScroll);
      }
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [currentIndex, isTransitioning, images]);

  // 监听currentIndex变化，执行图片切换动画
  useEffect(() => {
    if (!imagesRef.current[0] || !isInitialized) return; // 确保组件已初始化

    const currentImages = imagesRef.current;
    const image = images[currentIndex];

    // 只有在过渡状态下才执行动画，避免初始加载时的干扰
    if (isTransitioning) {
      // 更新文字内容
      gsap.to([titleRef.current, subtitleRef.current, descriptionRef.current], {
        opacity: 0,
        y: -20,
        duration: 0.3,
        ease: 'power2.out',
        onComplete: () => {
          if (titleRef.current) titleRef.current.textContent = image.title;
          if (subtitleRef.current) subtitleRef.current.textContent = image.subtitle;
          if (descriptionRef.current) descriptionRef.current.textContent = image.description;
          
          gsap.to([titleRef.current, subtitleRef.current, descriptionRef.current], {
            opacity: 1,
            y: 0,
            duration: 0.5,
            ease: 'power2.out',
            stagger: 0.1
          });
        }
      });

      // 切换图片显示
      currentImages.forEach((img, index) => {
        if (img) {
          gsap.to(img, {
            opacity: index === currentIndex ? 1 : 0,
            scale: index === currentIndex ? 1 : 0.95,
            duration: 0.6,
            ease: 'power2.out'
          });
        }
      });
    }

    // 更新计数器（这个总是需要更新）
    if (counterRef.current) {
      counterRef.current.textContent = `${(currentIndex + 1).toString().padStart(2, '0')} / ${images.length.toString().padStart(2, '0')}`;
    }

    // 更新滚动指示器（这个也总是需要更新）
    if (scrollIndicatorRef.current) {
      const scrollText = scrollIndicatorRef.current.querySelector('.scroll-text');
      if (scrollText) {
        scrollText.textContent = currentIndex === images.length - 1 ? '继续探索' : '滚动切换';
      }
    }
  }, [currentIndex, images, isTransitioning, isInitialized]);

  return (
    <section ref={heroRef} className="hero-section" id="home">
      <div className="hero-container">
        <div className="hero-content">
          <div ref={titleRef} className="hero-title">山川壮景</div>
          <div ref={subtitleRef} className="hero-subtitle">Mountain Majesty</div>
          <div ref={descriptionRef} className="hero-description">
            用镜头捕捉山峦叠嶂的壮美瞬间
          </div>
          <div ref={buttonsRef} className="hero-buttons">
            <button className="primary-btn">探索作品</button>
            <button className="secondary-btn">了解更多</button>
          </div>
        </div>
        
        <div ref={imageContainerRef} className="hero-image-container">
          {images.map((image, index) => (
            <div
              key={image.id}
              ref={(el) => {
                if (el) imagesRef.current[index] = el;
              }}
              className={`hero-image image-${index + 1}`}
            >
              <div className="image-placeholder">
                <span>{image.title}</span>
              </div>
            </div>
          ))}
          
          <div ref={counterRef} className="image-counter">01 / 05</div>
          
          {/* 进度指示器 */}
          <div className="progress-dots">
            {images.map((_, index) => (
              <div 
                key={index}
                className={`progress-dot ${index === currentIndex ? 'active' : ''}`}
                onClick={() => {
                  if (!isTransitioning && index !== currentIndex) {
                    setIsTransitioning(true);
                    setCurrentIndex(index);
                    setTimeout(() => {
                      setIsTransitioning(false);
                    }, 600);
                  }
                }}
              />
            ))}
          </div>
        </div>
      </div>
      
      <div ref={scrollIndicatorRef} className="scroll-indicator">
        <div className="scroll-text">{currentIndex === images.length - 1 ? '继续探索' : '滚动切换'}</div>
        <div className="scroll-line"></div>
      </div>
    </section>
  );
};

export default HeroSection;